// pages/distributionDetails/distributionDetails.js
let api = require('../../utils/api.js');
var utils = require('../../utils/util.js')
let regeneratorRuntime = require("../../utils/regenerator-runtime/runtime-module.js");
let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    data: {},
    mine: {},
    showModal1: false,
    showModal2: false,
    showModal3: false,
    TabCur: 0,
    scrollLeft: 0,
    tabList: [{
      id: '1',
      cate_name: '我的业绩'
    }, {
      id: '2',
      cate_name: '代理业绩'
    }, {
      id: '3',
      cate_name: '我的余额'
    }],
    tabList2: [{
      id: '1',
      cate_name: '我的业绩'
    }],
    date1: '',
    date2: '',
    cate_id: '1',
    page: 1,
    selectName: '',
    a: 1000,
    JE: '',
    bank_card:'',
    changeoffer:''
  },

  // 我的余额
  getBalance(that, params) {
    wx.request({
      url: `${app.globalData.host}distribution/my_balance`,
      data: params,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.code == '2000') {
          res.data.data.history.data.forEach(item => {
            item.create_time = that.getDate(new Date(item.create_time*1000))
          })
          let list = that.data.history
          let list1 = res.data.data.history.data
          if (params.page == 1) {
            list = list1
          } else {
            list = [...list, ...list1]
          }
          that.setData({
            all_cash: res.data.data.all_cash,
            allow_cash: res.data.data.allow_cash,
            history: list,
            historyLength: list1.length
          })
        } else {
          that.setData({
            code: res.data.code,
          })
        }
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  // 时间戳转换日期
  getDate(now) {
    var year = now.getFullYear(); //取得4位数的年份
    var month = now.getMonth() + 1; //取得日期中的月份，其中0表示1月，11表示12月
    var date = now.getDate(); //返回日期月份中的天数（1到31）
    var hour = now.getHours(); //返回日期中的小时数（0到23）
    var minute = now.getMinutes(); //返回日期中的分钟数（0到59）
    var second = now.getSeconds(); //返回日期中的秒数（0到59）
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
  },
  // 获取业绩
  getPerformance(that, params) {
    wx.request({
      url: `${app.globalData.host}distribution/my_achievement`,
      data: params,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.code == '2000') {
          that.setData({
            code: res.data.code,
            data: res.data.data.store,
            mine: res.data.data.mine,
            achievement: res.data.data.achievement
          })
        } else {
          that.setData({
            code: res.data.code,
          })
        }
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  // 显示修改窗口
  showEdit(e){
    let discount = e.currentTarget.dataset.discount
    let id = e.currentTarget.dataset.id
    this.setData({
      showModal3: true,
      discount,
      id
    })
  },
  //获取折扣
  changeoffer(e) {
    this.setData({
      changeoffer: e.detail.value
    })
  },
  // 修改折扣
  changeOff(){
    if(this.data.changeoffer==''||this.data.changeoffer>10||this.data.changeoffer<5){
      wx.showToast({
        title: '折扣不能为空且只能介于5-10之间',
        icon:'none'
      })
      return
    }
    let params={
      store_id:this.data.store_id,
      id:this.data.id,
      discount:this.data.changeoffer,
      token: wx.getStorageSync('token')
    }
    const that = this
    wx.request({
      url:app.globalData.host +'distribution/edit_discount',
      method:'POST',
      data:params,
      success(res){
        console.log(res)
        if(res.data.code==2000){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          setTimeout(function () {
            that.setData({
              showModal3: false
            })
          }, 1000)
          // that.setData({
          //   discount:res.data.discount,
          // })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      },
      fail(err){
        console.log(err)
      }
    })
   
  },
  //代理业绩
  agent(that, params) {
    wx.request({
      url: `${app.globalData.host}distribution/distribution_achievement`,
      data: params,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.code == '2000') { 
          let list = that.data.agentList
          let list1 = res.data.data.data
          if (params.page == 1) {
            list = list1
          } else {
            list = [...list, ...list1]
          }
          for (var index in list)
          that.setData({
            agentList: list,
            agentListLength: list1.length,
            page:res.data.data.current_page
          })
        }
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  // 复制推荐码
  copy() {
    wx.setClipboardData({
      data: this.data.referralCode,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  // 切换tab
  tabSelect(e) {
    if (e.currentTarget.dataset.idx == this.data.TabCur) {
      return
    }
    let cate_id = e.currentTarget.dataset.id
    console.log(cate_id)
    this.setData({
      TabCur: e.currentTarget.dataset.idx,
      scrollLeft: (e.currentTarget.dataset.idx - 1) * 90,
      cate_id
    })
    if (this.data.code == '2000' && cate_id == 2) {
      let params = {
        store_id: this.data.store_id,
        token: wx.getStorageSync('token'),
        page: this.data.page,
        search: this.data.keywords
      }
      let that = this
      this.agent(that, params)
    }
    if (this.data.code == '2000' && cate_id == 3) {
      let params = {
        store_id: this.data.store_id,
        token: wx.getStorageSync('token'),
        page: this.data.page,
      }
      let that = this
      this.getBalance(that, params)
      
    }
  },

  //搜索
  searchGoods(e) {
    var keywords = e.detail.value
    this.setData({
      keywords
    })

  },
  search1() {
    let that = this
    let params = {
      store_id: that.data.store_id,
      token: wx.getStorageSync('token'),
      page: that.data.page,
      search: that.data.keywords
    }
    that.agent(that, params)
  },

  // 申请
  handleApply() {
    this.setData({
      showModal: true
    })
  },

  // 取消
  cancel() {
    this.setData({
      showModal: false
    })
  },
  // 查看详情
  toDetails() {
    wx.navigateTo({
      url: '../order/order?store_id='+this.data.store_id,
    })
  },
  // 提现
  withdrawals() {
    this.setData({
      showModal1: true
    })
  },

  //获取提现金额
  JE(e) {
    this.setData({
      JE: e.detail.value
    })
    if(this.data.JE>this.data.allow_cash){
      wx.showToast({
        title: '提现金额不能大于可提现金额',
        icon:'none'
      })
      this.setData({
        JE: this.data.allow_cash
      })
    }
  },
  //获取提现人真实姓名
  getRailName(e) {
    this.setData({
      railName: e.detail.value
    })
  },
  // 取消
  cancel1() {
    this.setData({
      showModal1: false,
      showModal3: false
    })
  },
  confirmTrue1() {
    let that = this
    if (that.data.JE == '') {
      return wx.showToast({
        title: '提现金额不能为空',
        icon: 'none'
      })
      
    }  else if( that.data.railName==''){
      return wx.showToast({
        title: '真实姓名不能为空',
        icon: 'none'
      })
    }
    else {
      let params={
        token: wx.getStorageSync('token'),
        price: that.data.JE,
        openid:wx.getStorageSync('openid'),
        store_id: that.data.store_id,
        true_name:that.data.railName
      }
      // 发送提现请求
      wx.request({
        url: app.globalData.host + 'PaymentTransfer/transfer_agent',
        method: 'POST',
        data:params,
        success(res) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          if (res.data.code == 2000) {
            that.setData({
              showModal1: false
            })
            let params = {
              store_id: that.data.store_id,
              token: wx.getStorageSync('token'),
              page: that.data.page,
            }
            that.getBalance(that, params)
          }else{
            that.setData({
              showModal1: true
            })
          }
        },
        fail(err) {}
      })
    }

  },


  // 提交
  async confirmTrue() {
    const that = this
    wx.request({
      url: app.globalData.host + 'distribution/apply',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        store_id: this.data.data.id,
        up_id: this.data.up_id,
        service_id: this.data.service_id
      },
      success(res) {
        if (res.data.code == 2000) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          that.setData({
            showModal: false,
            code: '2002'
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      },
      fail(err) {}
    })
  },

  // 搜索推荐码
  async select(e) {
    const that = this;
    wx.request({
      url: app.globalData.host + 'distribution/code_search',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        code: e.detail.value
      },
      success(res) {
        console.log(res.data)
        if (res.data.code == 2000) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          that.setData({
            store_id: res.data.data.store_id,
            up_id: res.data.data.up_id,
            service_id: res.data.data.service_id,
            selectName: res.data.data.name
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      },
      fail(err) {}
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.setData({
      date1: utils.formatTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
      date2: utils.formatTime(new Date()),
      store_id: JSON.parse(options.data).id,
      code: JSON.parse(options.data).code,
      data: JSON.parse(options.data),
    })
    let params = {
      store_id: that.data.store_id,
      start_time: new Date(that.data.date1).getTime(),
      end_time: new Date(that.data.date2).getTime(),
      token: wx.getStorageSync('token')
    }
    if (that.data.code == 2000) {
      that.getPerformance(that, params)
    }
  },

  //时间起
  dateChange1(e) {
    let that = this
    that.setData({
      date1: e.detail.value
    })
    let params = {
      store_id: that.data.store_id,
      start_time: new Date(that.data.date1).getTime(),
      end_time: new Date(that.data.date2).getTime(),
      token: wx.getStorageSync('token')
    }
    that.getPerformance(that, params)
  },

  //时间止
  dateChange2(e) {
    let that = this
    that.setData({
      date2: e.detail.value
    })
    let params = {
      store_id: that.data.store_id,
      start_time: new Date(that.data.date1).getTime(),
      end_time: new Date(that.data.date2).getTime(),
      token: wx.getStorageSync('token')
    }
    that.getPerformance(that, params)
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.cate_id == 2) {
      var page = this.data.page || 1;
      page++;
      if (this.data.agentListLength < 10) {
        wx.showToast({
          title: '暂无更多',
          icon: 'none'
        })
        return
      }
      let that = this
      let params = {
        store_id: that.data.store_id,
        token: wx.getStorageSync('token'),
        page: page,
        search: that.data.keywords
      }
      that.agent(that, params)
    }
    if(this.data.cate_id == 3){
      var page = this.data.page || 1;
      page++;
      if (this.data.historyLength < 10) {
        wx.showToast({
          title: '暂无更多',
          icon: 'none'
        })
        return
      }
      let that = this
      let params = {
        store_id: this.data.store_id,
        token: wx.getStorageSync('token'),
        page: this.data.page,
      }
      this.getBalance(that, params)
    }
  }
})